<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>策略模式-表单校验</title>
    <style>
      span {
        display: inline-block;
        width: 130px;
      }
    </style>
  </head>
  <body>
    <form action="" id="registerForm" method="post">
      <span>请输入用户名：</span> <input type="text" name="userName" />
      <br />
      <span>请输入密码：</span> <input type="text" name="passWord" />
      <br />
      <span>请输入手机号码：</span> <input type="text" name="phoneNumber" />
      <button>提交</button>
    </form>
    <script>
      var strategies = {
        isNonEmpty: function (value, errorMsg) {
          if (value === "") {
            return errorMsg;
          }
        },
        minLength: function (value, length, errorMsg) {
          if (value.length < length) {
            return errorMsg;
          }
        },
        isMobile: function (value, errorMsg) {
          if (!/(^1[3|5|8][0-9]{9}$)/.test(value)) {
            return errorMsg;
          }
        },
      };

      var Validator = function () {
        this.cache = [];
      };
      Validator.prototype.add = function (dom, rule, errorMsg) {
        var ary = rule.split(":");
        this.cache.push(function () {
          var strategy = ary.shift();
          ary.unshift(dom.value);
          ary.push(errorMsg);
          return strategies[strategy].apply(dom, ary);
        });
      };
      Validator.prototype.start = function () {
        for (var i = 0, validatorFunc; (validatorFunc = this.cache[i++]); ) {
          var msg = validatorFunc();
          if (msg) {
            return msg;
          }
        }
      };

      var validatorFunc = function () {
        var validator = new Validator();
        validator.add(registerForm.userName, "isNonEmpty", "用户名不能为空");
        validator.add(
          registerForm.passWord,
          "minLength:6",
          "密码长度不能少于6位"
        );
        validator.add(
          registerForm.phoneNumber,
          "isMobile",
          "手机号码格式不正确"
        );

        var errorMsg = validator.start();
        return errorMsg;
      };

      var registerForm = document.getElementById("registerForm");
      registerForm.onsubmit = function () {
        var errorMsg = validatorFunc();
        if (errorMsg) {
          alert(errorMsg);
          return false;
        }
      };
    </script>
  </body>
</html>
